package cn.edu.scau.cmi.yewangjiang.hibernate.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.edu.scau.cmi.yewangjiang.hibernate.domain.Student;
import cn.edu.scau.cmi.yewangjiang.hibernate.util.SessionFactoryUnit;
/*
 * 使用Hibernate操作数据的流程是：
读取并解析配置文件 -----读取并解析映射文件，创建SessionFactory
------打开session-------开启一个事务-------操作数据库--------提交或者回滚事务-------关闭session。

 */


public class StudentDAO {
    private Session session = null; 

    private Session getSession() {
        if (session == null) {
            session = SessionFactoryUnit.getSession();
        }
        return session;
    }

    public boolean save(Student student) {
        Transaction ts = getSession().beginTransaction();
        try {
            getSession().save(student);
            ts.commit();
            return true;
        } catch (Exception e) {
            throw e;
        }
    }

    public boolean update(Student student) {
        Transaction ts = getSession().beginTransaction();
        try {
            getSession().update(student);
            ts.commit();
            return true;
        } catch (Exception e) {
            throw e;
        }
    }

    public boolean delete(Student student) {
        Transaction ts = getSession().beginTransaction();
        try {
            getSession().delete(student);
            ts.commit();
            return true;
        } catch (Exception e) {
            throw e;
        }
    }

    public List findAll() {
        try {
            Query q = getSession().createQuery("from Student");
            return q.list();
        } catch (Exception e) {
            return null;
        }
    }

    public List findByName(Object name) {
        try {
            String queryString = "from Student as model where model." + "name" + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, name);
            return queryObject.list();
        } catch (RuntimeException re) {
            return null;
        }
    }
}
